package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

type Alert struct {
	Labels       map[string]string `json:"labels"`
	Annotations  map[string]string `json:annotations`
	StartsAt     time.Time         `json:"startsAt"`
	EndsAt       time.Time         `json:"endsAt"`
	Status       string            `json:"status"`
	GeneratorURL string            `json:"generatorURL"`
}

type Notification struct {
	Version           string            `json:"version"`
	GroupKey          string            `json:"groupKey"`
	Status            string            `json:"status"`
	Receiver          string            `json:receiver`
	GroupLabels       map[string]string `json:groupLabels`
	CommonLabels      map[string]string `json:commonLabels`
	CommonAnnotations map[string]string `json:commonAnnotations`
	ExternalURL       string            `json:externalURL`
	Alerts            []Alert           `json:alerts`
}


func main() {
	router := gin.Default()
	router.POST("/alert", handleMsg)
	router.Run(":8333")
}

func handleMsg( c *gin.Context){
	var notification Notification
	var err error
	err = c.BindJSON(&notification)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	SendMsgToWebhook(&notification)
}

func SendMsgToWebhook(notification *Notification) {
	var alerts = notification.Alerts
	var webhook = ""

	for _, alert := range alerts {
		var startsAt =alert.StartsAt
		var status = alert.Status
		var description = alert.Annotations["description"]
		postData1 := map[string]interface{}{
			"msg_type": "text",
			"content":  fmt.Sprintf(`{"text":"告警状态：%s\n告警时间：%s\n告警信息：%v\n"}`, status,startsAt, description),
		}
		sendMsg,err:=json.Marshal(postData1)
		req, err := http.NewRequest("POST", webhook, bytes.NewBuffer(sendMsg))
		req.Header.Set("Content-Type", "application/json")
		client := &http.Client{}
		resp, err := client.Do(req)
		defer resp.Body.Close()
		if err != nil {
			log.Printf("post feishu webhook error, error is %v", err.Error())
		}
		log.Printf("post feishu %v alert status: %v\n", alert.Annotations["description"], resp.Status)
	}
}